#!/bin/sh

#############################
#                           #
#  Write by iceblood        #
#    iceblood@163.com       #
#############################


PATH=/bin:/sbin:/usr/bin:/usr/sbin

OLDDISK=$1
DISK=$2

help()
{
	cat << HELP
$0 {id|device} [newdevice]
EXAMPLES:
	$0 da0
	$0 23453214742366 da1
HELP
}

if [ "$DISK" = "" ]; then
	DISK=$OLDDISK
fi
if [ "$DISK" = "" ]; then
	help;
	exit 1
fi
if [ ! -e /dev/$DISK ]; then
	echo "Sorry!!!Not exist \"/dev/$DISK\" !!!"
	exit 1
fi
POOLLIST=$(zpool list | sed 1d | awk '{print $1}' | tr '\n' ' ' | sed 's/ $//')
DEFPOOL=$(echo $POOLLIST | awk '{print $1}')
echo -n "Please input pool:${POOLLIST} default[${DEFPOOL}]"
read POOL
if [ "$POOL" = "" ]; then
	POOL=$DEFPOOL
fi
zpool list | sed 1d | awk '{print $1}' | grep -q "^${POOL}$" || (echo "Sorry!not this pool!!!"; exit 1) || exit 1
gpart destroy -F ${DISK} > /dev/null 2>&1
DISKLABEL=`zpool status $POOL | grep '/dev/gpt/' | awk '{print $7}' | sed 's/\/dev\/gpt\///;s/.nop//'`
if [ "$DISKLABEL" = "" ]; then
	DISKCOUNT=0
	while [ "`gpart list | grep 'label: ' | grep $POOL-disk${DISKCOUNT}`" != "" ]; do
		DISKCOUNT=`expr $DISKCOUNT + 1`
	done
	DISKLABEL=$POOL-disk${DISKCOUNT}
fi
gpart create -s gpt $DISK > /dev/null 2>&1
gpart add -b 34 -s 64k -t freebsd-boot $DISK > /dev/null 2>&1
gpart add -t freebsd-zfs -a 4k -l $DISKLABEL $DISK > /dev/null 2>&1
gpart bootcode -b /boot/pmbr -p /boot/gptzfsboot -i 1 $DISK > /dev/null 2>&1
if [ "$DISK" = "$OLDDISK" ]; then
	gnop create -S 4096 /dev/gpt/$DISKLABEL
	zpool replace -f $POOL /dev/gpt/$DISKLABEL.nop
else
	gnop create -S 4096 /dev/gpt/$DISKLABEL
	zpool replace -f $POOL $OLDDISK /dev/gpt/$DISKLABEL.nop
fi